package com.marcandjo.gwtproject.client.model.impl;

import java.util.ArrayList;
import java.util.List;

import com.marcandjo.gwtproject.client.model.Category;
import com.marcandjo.gwtproject.client.model.Photo;
import com.marcandjo.gwtproject.client.model.PhotoModel;
import com.marcandjo.gwtproject.client.model.PhotoModelListener;

public class PhotoModelImpl implements PhotoModel 
{
	protected List<Category> model;
	protected List<PhotoModelListener> listeners;
	
	public PhotoModelImpl()
	{
		model = new ArrayList<Category>();
	}
	
	public void add(Category category, Photo photo) 
	{
		Category categoryToModify = null;
		
		if (model.indexOf(category) != -1) categoryToModify = model.get(model.indexOf(category));
		else
		{ 
			categoryToModify = category;
			model.add(categoryToModify);
		}
			
		categoryToModify.add(photo);
		
		fireListeners();
	}

	public void addListener(PhotoModelListener listener) 
	{
		listeners.add(listener);
	}

	public List<Category> getModel() 
	{
		return model;
	}

	public void remove(Category category, Photo photo) 
	{
		Category categoryToModify = null;
		
		if (model.indexOf(category) != -1)
		{
			categoryToModify = model.get(model.indexOf(category));
			categoryToModify.remove(photo);
			
			fireListeners();
		}
	}

	public void removeListener(PhotoModelListener listener) 
	{
		listeners.remove(listener);
	}

	private void fireListeners()
	{
		for (PhotoModelListener listener : listeners)
		{
			listener.onModelChanged();
		}
	}
}
